#! /usr/bin/env python
import urllib2, GraphData_pb2

OUTPUT_FILE = "6NodeGraph.buf"

def main():
    GRAPH_URL = "http://www.public.asu.edu/~hvachhan/6NodeGraph.txt"
    
    graph_data = GraphData_pb2.Graph()
    
    print "Starting download of graphdata"
    webSrcPage = urllib2.urlopen( GRAPH_URL )
    
    webSrc = webSrcPage.read().split( "\n" )
    print "Done getting the graph, parsing now"
    
    numOfLines = len( webSrc )
    
    lineIndex = 0
    while lineIndex < numOfLines:
        if webSrc[ lineIndex ].find( "node" ) != -1:
            newNode = graph_data.nodes.add()
            while webSrc[ lineIndex ].find( "]" ) == -1:
                if webSrc[ lineIndex ].find( "id" ) != -1:
                    splitList = webSrc[ lineIndex ].split( " " )
                    newNode.ID = int( splitList[ len( splitList ) - 1 ] )
                    lineIndex += 1
                else:
                    lineIndex += 1
        elif webSrc[ lineIndex ].find( "edge" ) != -1:
            newEdge = graph_data.edges.add()
            while webSrc[ lineIndex ].find( "]" ) == -1:
                if webSrc[ lineIndex ].find( "source" ) != -1:
                    splitList = webSrc[ lineIndex ].split( " " )
                    newEdge.source = int( splitList[ len( splitList ) - 1 ] )
                    lineIndex += 1
                elif webSrc[ lineIndex ].find( "target" ) != -1:
                    splitList = webSrc[ lineIndex ].split( " " )
                    newEdge.target = int( splitList[ len( splitList ) - 1 ] )
                    lineIndex += 1
                else:
                    lineIndex += 1
        else:
            lineIndex += 1
            
            
    outputFile = open( OUTPUT_FILE, 'w' )
    outputFile.write( graph_data.SerializeToString() )
    outputFile.close()    
    
    print "Finished"

if __name__ == "__main__":
    main()
